package org.Agenty2012.Agent;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;

public class MyLocationListener implements LocationListener {

	private String sid;
	private String address;
	
	public MyLocationListener(String sid, String address)
	{
		super();
		this.sid = sid;
		this.address = address;
	}
	
	@Override
	public void onLocationChanged(Location location) {
		postData(location.getLatitude(), location.getLongitude());		
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
	
	private void postData(double lat, double lon) {
        // Create a new HttpClient and Post Header
    	//String baseUrl = "http://10.0.2.2:1785/Locations.asmx";
    	String baseUrl = address + "/Locations.asmx";
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(baseUrl+"/AddLocation");// + "?nickname=" + name + "&color=" + color);
 
        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
            nameValuePairs.add(new BasicNameValuePair("sid", sid));
            nameValuePairs.add(new BasicNameValuePair("lat", String.valueOf(lat)));
            nameValuePairs.add(new BasicNameValuePair("lon", String.valueOf(lon)));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            httppost.setHeader("Content-type", "application/x-www-form-urlencoded");

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            if (response != null)
            	Log.d(getClass().getSimpleName(),"otrzymal odpowiedz");
           // String s = inputStreamToString(response.getEntity().getContent()).toString();
           // String ss = "tomek";
            
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    }

}
